/**
 * Copyright (c) 2018-2028, Joffee.
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.sailmi.system.controller;


import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.read.builder.ExcelReaderBuilder;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.sailmi.common.constant.AppConstant;
import com.sailmi.common.model.auth.AuthInfo;
import com.sailmi.common.model.auth.AuthUser;
import com.sailmi.common.mybatis.support.Condition;
import com.sailmi.common.mybatis.support.Query;
import com.sailmi.common.tool.api.R;
import com.sailmi.common.tool.jackson.JsonUtil;
import com.sailmi.common.tool.utils.Func;
import com.sailmi.common.tool.utils.SecureUtil;
import com.sailmi.common.tool.utils.UrlUtil;
import com.sailmi.system.entity.UserEnterprise;
import com.sailmi.system.excel.UserExcel;
import com.sailmi.system.excel.UserImportListener;
import com.sailmi.system.service.IUserService;
import com.sailmi.system.entity.UcsAccountuser;
import com.sailmi.system.entity.User;
import com.sailmi.system.vo.UserVO;
import com.sailmi.system.service.impl.UserEnterpriseServiceImpl;
import com.sailmi.system.wrapper.UserWrapper;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.commons.codec.Charsets;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.validation.Valid;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * 控制器
 *
 * @author Joffee
 */
@RestController
@RequestMapping("/user")
public class UserController {
	@Resource
	private IUserService userService;
	@Resource
	private UserEnterpriseServiceImpl userEnterpriseServiceImpl;

	/**
	 * 注册用户
	 * @param user
	 * @return
	 */
	@PostMapping("/register")
	@Operation(summary = "注册用户", description = "传入UcsAccountuser")
	public R registerUser(@RequestBody UcsAccountuser user) {
		String s = userService.registerUser(user);
		if(s.equals("fail")){
			return R.fail("验证码错误");
		}else if(s.equals("success")){
			return R.success("注册成功");
		}else{
			return R.fail("验证码超时");
		}
	}

	/**
	 * 发送短信验证码
	 * @param userPhone
	 * @return
	 */
	@PostMapping("/sendPhoneCode")
	@Operation(summary = "发送验证码短信", description = "传入userPhone")
	public R sendPhoneCode(@RequestParam(name="userPhone") String userPhone) {
		return R.status(userService.sendPhoneCode(userPhone));
	}

	/**
	 * 验证手机号唯一
	 * @param userPhone
	 * @return
	 */
	@PostMapping("/uniquePhone")
	@Operation(summary = "验证手机号唯一", description = "传入userPhone")
	public R queryPhoneCode(@RequestParam(name="userPhone") String userPhone) {
		long count = userService.queryUnikePhone(userPhone);
		if(count>0){
			return R.fail("该手机号已经被注册");
		}else{
			return R.success("可以使用该手机号");
		}

	}

	/**
	 * 查询单条
	 */
	@Operation(summary = "查看用户基础信息详情", description = "传入id")
	@GetMapping("/detail")
	public R<UserVO> detail(Long id) {
		User detail = new User();
		detail.setId(id);
		detail = userService.getOne(Condition.getQueryWrapper(detail));
		return R.data(UserWrapper.build().entityVO(detail));
	}

	/**
	 * 查询单条
	 */
	@Operation(summary = "查看用户综合信息详情", description = "传入id")
	@GetMapping("/info")
	public R<UserVO> info(AuthUser user) {
		System.out.println("AuthUser:"+user);
		User detail = userService.getById(user.getUserId());
		return R.data(UserWrapper.build().entityVO(detail));
	}

	/**
	 * 用户列表
	 */
	@GetMapping("/list")
	@Operation(summary = "列表", description = "传入account和realName")
	public R<IPage<UserVO>> list(@RequestParam(name="account",required = false) String account, @RequestParam(name="realName",required = false) String realName, @ModelAttribute Query query, HttpServletRequest request) {
		AuthInfo authInfo = SecureUtil.getAuthInfo();
		User user = new User();
		if(Objects.nonNull(account)) user.setAccount(account);
		if(Objects.nonNull(realName)) user.setRealName(realName);
		QueryWrapper<User> queryWrapper = Condition.getQueryWrapper(user);
		ArrayList<Long> userIds = new ArrayList<>();
		if(authInfo!=null) {
			if(authInfo.getTenantId().equals("000000")){//平台管理员
				//查询所有租户的管理员列表
				if (authInfo.getEnterprise() != null) {

					List<UserEnterprise> listR = detailInfo(authInfo.getEnterprise(),true);
					if(Objects.nonNull(listR)){
						listR.stream().forEach(userEnter->{
							userIds.add(userEnter.getUserId());
						});
					}
				}
			}else{//租户管理员
				if (authInfo.getEnterprise() != null) {
					List<UserEnterprise> listR = detailInfo(authInfo.getEnterprise(),false);
					if(Objects.nonNull(listR)){
						listR.stream().forEach(userEnter->{
							userIds.add(userEnter.getUserId());
						});
					}
				}
			}

		}
		if(userIds.size()>0){
			queryWrapper.in("id",userIds);
		}else{
			queryWrapper.in("id",0);
		}
			IPage<User>	pages = userService.page(Condition.getPage(query),  queryWrapper);
			return R.data(UserWrapper.build().pageVO(pages));
	}

	/**
	 * 新增或修改
	 */
	@PostMapping("/submit")
	@Operation(summary = "新增或修改", description = "传入User")
	public R submit(@Valid @RequestBody User user) {
		return R.status(userService.submit(user));
	}

	/**
	 * 修改
	 */
	@PostMapping("/update")
	@Operation(summary = "修改", description = "传入User")
	public R update(@Valid @RequestBody User user) {
		return R.status(userService.updateById(user));
	}

	/**
	 * 删除
	 */
	@PostMapping("/remove")
	@Operation(summary = "删除", description = "传入要操作的用户ID列表")
	public R remove(@RequestParam String ids) {
		return R.status(userService.deleteLogic(Func.toLongList(ids)));
	}


	/**
	 * 设置菜单权限
	 *
	 * @param userIds
	 * @param roleIds
	 * @return
	 */
	@PostMapping("/grant")
	@Operation(summary = "权限设置", description = "传入roleId集合以及menuId集合")
	public R grant(@Parameter(name = "userId集合", required = true) @RequestParam String userIds,
				   @Parameter(name = "roleId集合", required = true) @RequestParam String roleIds) {
		boolean temp = userService.grant(userIds, roleIds);
		return R.status(temp);
	}

	@PostMapping("/reset-password")
	@Operation(summary = "初始化密码", description = "传入userId集合")
	public R resetPassword(@Parameter(name = "userId集合", required = true) @RequestParam String userIds) {
		boolean temp = userService.resetPassword(userIds);
		return R.status(temp);
	}

	/**
	 * 修改密码
	 *
	 * @param oldPassword
	 * @param newPassword
	 * @param newPassword1
	 * @return
	 */
	@PostMapping("/update-password")
	@Operation(summary = "修改密码", description = "传入密码")
	public R updatePassword(AuthUser user, @Parameter(name = "旧密码", required = true) @RequestParam String oldPassword,
							@Parameter(name = "新密码", required = true) @RequestParam String newPassword,
							@Parameter(name = "新密码", required = true) @RequestParam String newPassword1) {
		boolean temp = userService.updatePassword(user.getUserId(), oldPassword, newPassword, newPassword1);
		return R.status(temp);
	}

	/**
	 * 用户列表
	 *
	 * @param user
	 * @return
	 */
	@GetMapping("/user-list")
	@Operation(summary = "用户列表", description = "传入user")
	public R<List<User>> userList(User user) {
		List<User> list = userService.list(Condition.getQueryWrapper(user));
		return R.data(list);
	}


	/**
	 * 导入用户
	 */
	@PostMapping("import-user")
	@Operation(summary = "导入用户", description = "传入excel")
	public R importUser(MultipartFile file, Integer isCovered) {
		String filename = file.getOriginalFilename();
		if (StringUtils.isEmpty(filename)) {
			throw new RuntimeException("请上传文件!");
		}
		if ((!StringUtils.endsWithIgnoreCase(filename, ".xls") && !StringUtils.endsWithIgnoreCase(filename, ".xlsx"))) {
			throw new RuntimeException("请上传正确的excel文件!");
		}
		InputStream inputStream;
		try {
			UserImportListener importListener = new UserImportListener(userService);
			inputStream = new BufferedInputStream(file.getInputStream());
			ExcelReaderBuilder builder = EasyExcel.read(inputStream, UserExcel.class, importListener);
			builder.doReadAll();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return R.success("操作成功");
	}

	/**
	 * 导出用户
	 */
	@GetMapping("export-user")
	@Operation(summary = "导出用户", description = "传入user")
	public void exportUser(@RequestParam Map<String, Object> user, AuthUser authUser, HttpServletResponse response) {
		QueryWrapper<User> queryWrapper = Condition.getQueryWrapper(user, User.class);
		if (!SecureUtil.isAdministrator()){
			queryWrapper.lambda().eq(User::getDefaultEnterpriseId, authUser.getTenantId());
		}
		queryWrapper.lambda().eq(User::getIsDeleted, AppConstant.DB_NOT_DELETED);
		List<UserExcel> list = userService.exportUser(queryWrapper);
		response.setContentType("application/vnd.ms-excel");
		response.setCharacterEncoding(Charsets.UTF_8.name());
		String fileName = null;
		fileName = URLEncoder.encode("用户数据导出", Charsets.UTF_8);
		response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
		try {
			EasyExcel.write(response.getOutputStream(), UserExcel.class).sheet("用户数据表").doWrite(list);
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
	}

	/**
	 * 导出模板
	 */
	@GetMapping("export-template")
	@Operation(summary = "导出模板")
	public void exportUser(HttpServletResponse response) {
		List<UserExcel> list = new ArrayList<>();
		response.setContentType("application/vnd.ms-excel");
		response.setCharacterEncoding(Charsets.UTF_8.name());
		String fileName = null;
		fileName = URLEncoder.encode("用户数据模板", Charsets.UTF_8);
		response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
		try {
			EasyExcel.write(response.getOutputStream(), UserExcel.class).sheet("用户数据表").doWrite(list);
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
	}

	public List<UserEnterprise> detailInfo(String enterpriseId, Boolean flag) {
		QueryWrapper<UserEnterprise> userEnterpriseQueryWrapper = new QueryWrapper<>();
		userEnterpriseQueryWrapper.eq("enterprise_id",enterpriseId);
		if(flag){
			userEnterpriseQueryWrapper.eq("status",1);//查询管理员列表
		}
		List<UserEnterprise> list = userEnterpriseServiceImpl.list(userEnterpriseQueryWrapper);
		return list;
	}

	/**
	 * 第三方注册用户
	 */
	@PostMapping("/register-guest")
	@Operation(summary = "第三方注册用户", description = "传入user")
	public R registerGuest(User user, Long oauthId) {
		return R.status(userService.registerGuest(user, oauthId));
	}
}
